import {
  deleteServiceProjectUsingPost,
  listServiceProjectByPageUsingPost,
} from '@/services/backend/serviceProjectController';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProFormInstance,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import { Button, message, Space, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import CreateModal from './components/CreateModal';
import UpdateModal from './components/UpdateModal';

const TableList: React.FC = () => {
  const [params] = useSearchParams();
  const id = (params.get('id') ?? -1) as number;
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.ServiceProject>();

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param row
   */
  const handleDelete = async (row: API.ServiceProject) => {
    const hide = message.loading('正在删除');
    if (!row) return true;
    try {
      await deleteServiceProjectUsingPost({
        id: row.id,
      });
      hide();
      message.success('删除成功');
      actionRef?.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败，' + error.message);
      return false;
    }
  };

  /**
   * 初始化钩子
   */
  useEffect(() => {
    //当id存在时,进行条件查询
    if (id !== -1) {
      formRef.current?.setFieldsValue({
        id: id,
      });
      formRef.current?.submit();
    }
  }, []);

  const statusEnumMap = new Map([
    [0, { text: '关闭', status: 'Error' }],
    [1, { text: '开启', status: 'Success' }],
  ]);

  const columns: ProColumns<API.ServiceProject>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '标题',
      dataIndex: 'title',
      valueType: 'text',
      ellipsis: true,
      tooltip: { title: '省略过长内容' },
    },
    {
      title: '介绍文档',
      dataIndex: 'introduce',
      valueType: 'textarea',
      ellipsis: {
        showTitle: false,
      },
      tooltip: { title: '省略过长内容' },
      hideInSearch: true,
    },
    {
      title: '价格',
      dataIndex: 'price',
      valueType: 'digit',
      width: 'xs',
      hideInSearch: true
    },
    {
      title: '展示图片',
      dataIndex: 'cover',
      valueType: 'image',
      fieldProps: {
        width: 64,
      },
      hideInSearch: true,
    },
    {
      title: '访问数',
      dataIndex: 'clickNum',
      valueType: 'digit',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: statusEnumMap,
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space size={'middle'}>
          <Typography.Link
            key="config"
            onClick={() => {
              setUpdateModalVisible(true);
              setCurrentRow(record);
            }}
          >
            修改
          </Typography.Link>
          <Typography.Link
            type="danger"
            onClick={() => {
              handleDelete(record);
            }}
          >
            删除
          </Typography.Link>
        </Space>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.ServiceProject>
        formRef={formRef}
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listServiceProjectByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.ServiceProjectQueryRequest);
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
      {/*新增悬浮窗*/}
      <CreateModal
        modalVisible={createModalVisible}
        columns={columns}
        onSubmit={() => {
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setCreateModalVisible(false);
        }}
      />
      {/*更新悬浮窗*/}
      <UpdateModal
        oldData={currentRow}
        modalVisible={updateModalVisible}
        columns={columns}
        onSubmit={() => {
          setUpdateModalVisible(false);
          setCurrentRow(undefined);
          actionRef.current?.reload();
        }}
        onCancel={() => {
          setUpdateModalVisible(false);
        }}
      />
    </PageContainer>
  );
};
export default TableList;
